package com.zd.miko.tally.MVP.PageTally;

import android.content.Context;

import com.zd.miko.tally.Bean.RealmBean.RealmTallyItem;
import com.zd.miko.tally.R;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import io.realm.Realm;

/**
 * Created by Miko on 2017/7/6.
 */

public class TallyPresenter implements TallyContract.Presenter {

    Context context;
    TallyContract.View activity;

    public TallyPresenter(Context context, TallyContract.View activity) {
        this.context = context;
        this.activity = activity;
        this.activity.setPresenter(this);
    }

    @Override
    public void start() {

    }

    /**
     * 初始化tally的条目存储到数据库中
     */
    public void initTallyItem() {
        Realm realm = Realm.getDefaultInstance();
        //解析text文件

        try {
            //获取文件中的内容
            InputStream inputStream = context.getResources().openRawResource(R.raw.item_list);
            //将文件中的字节转换为字符
            InputStreamReader isReader = new InputStreamReader(inputStream, "UTF-8");
            //使用bufferReader去读取字符
            BufferedReader reader = new BufferedReader(isReader);
            String out = "";
            try {
                while ((out = reader.readLine()) != null) {
                    String[] itemArray = out.split(" ");
                    realm.executeTransaction(realm1 -> {
                        RealmTallyItem item = new RealmTallyItem();
                        item.setName(itemArray[0]);
                        item.setResId(itemArray[1]);
                    });
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
